<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">砍价详情</block>
		</cu-custom>
		<view class="cu-card article"  v-if="bargainInfo.goodsSku">
			<view class="cu-item" v-if="bargainInfo.bargainUser&&bargainInfo.bargainUser.status == '0'">
				<view class="content margin-top">倒计时：<count-down class="text-red" :outTime="dateUtil.getOutTime(bargainInfo.bargainUser.validEndTime)"
					 @countDownDone="countDownDone"></count-down>
				</view>
			</view>
			<view class="cu-item padding-top">
				<navigator v-if="theme.showType!=2"  class="padding-lr padding-bottom" hover-class="none" :url="'/pages/shop/shop-detail/index?id=' + bargainInfo.shopInfo.id">
					<view class="cu-avatar sm radius" :style="'background-image:url(' + bargainInfo.shopInfo.imgUrl + ')'"></view>
					<text class="text-black text-bold margin-left-sm">{{bargainInfo.shopInfo.name}}</text>
					<text class="cuIcon-right text-sm"></text>
				</navigator>
				<view class="margin-left-sm">
					<view class="action">
						<text class="cuIcon-hotfill margin-right-xs" :class="'text-'+theme.themeColor"></text>{{bargainInfo.name}}
					</view>
					<view class="flex justify-between margin-xs">
						<text class="text-sm text-gray margin-left-sm" v-if="bargainInfo.launchNum">已有{{bargainInfo.launchNum}}人参与</text>
						<text class="text-blue text-sm margin-right-sm" @tap="ruleShow">砍价规则</text>
					</view>
				</view>
				<view class="content">
					<image :src="bargainInfo.picUrl" mode="aspectFill" class="row-img margin-top-xs"></image>
					<view class="desc">
						<view class="text-black margin-top-sm overflow-2">{{bargainInfo.goodsSpu.name}}</view>
						<view class="text-gray text-sm overflow-1" v-if="bargainInfo.goodsSku&&bargainInfo.goodsSku.specs&&bargainInfo.goodsSku.specs.length > 0">{{specInfo}}</view>
						<view class="flex justify-start margin-top-sm align-center">
							<view class="text-price text-bold text-xl text-red">{{bargainInfo.bargainPrice}}</view>
							<view class="text-price text-decorat text-gray margin-left-sm">{{bargainInfo.goodsSku.salesPrice}}</view>
							<view class="cu-tag bg-red radius sm margin-left" v-if="bargainInfo.goodsSpu.freightTemplat.type == '2'">包邮</view>
						</view>

					</view>
				</view>
				<view class="padding-lr text-center margin-top-sm" v-if="bargainInfo">
					<!-- 没参与 -->
					<view v-if="!(bargainInfo.bargainUser && hasBargainUser)">
						<button class="cu-btn bargain-btn round lg shadow-blur" :class="'bg-'+theme.themeColor" v-if="bargainInfo.enable == '1' && bargainInfo.status == '1'"
						 :disabled="disabled" @tap="bargainUserSave"><text class="cuIcon-cardboardforbid">发起砍价</text></button>
						<button class="cu-btn bargain-btn radius lg bg-gray" v-if="bargainInfo.enable == '0'"><text class="cuIcon-cardboardforbid">该砍价已关闭</text></button>
						<button class="cu-btn bargain-btn round bg-gray lg shadow-blur" v-if="bargainInfo.status == '0'"><text class="cuIcon-cardboardforbid">活动未开始</text></button>
						<button class="cu-btn bargain-btn round bg-gray lg shadow-blur margin-top-sm" v-if="bargainInfo.status == '2'"><text class="cuIcon-close">活动已过期</text></button>
						<view class="text-gray text-sm margin-top" v-if="bargainInfo.validBeginTime">{{bargainInfo.validBeginTime}}至{{bargainInfo.validEndTime}}</view>
					</view>
					<!-- 已经参与 -->
					<view v-if="bargainInfo.bargainUser && hasBargainUser">
						<view class="text-gray text-sm margin-top margin-bottom-sm">{{bargainInfo.bargainUser.validBeginTime}}至{{bargainInfo.bargainUser.validEndTime}}</view>
						<button class="cu-btn bargain-btn round lg shadow-blur" :class="'bg-'+theme.themeColor" v-if="bargainInfo.enable == '1' && bargainInfo.bargainUser.status == '0'"
						@click="shareShowFun"><text class=" cuIcon-friend">邀请好友帮砍</text></button>
						<button class="cu-btn bargain-btn radius lg bg-gray" v-if="bargainInfo.enable == '0'"><text class="cuIcon-cardboardforbid">该砍价已关闭</text></button>
						<button class="cu-btn bargain-btn round bg-orange lg shadow-blur" v-if="bargainInfo.bargainUser.status == '1'"><text class=" cuIcon-check">已完成砍价</text></button>
						<button class="cu-btn bargain-btn round bg-gray lg shadow-blur" v-if="bargainInfo.bargainUser.status == '2'"><text class=" cuIcon-close">活动已过期</text></button>

					</view>
				</view>
				<view class="padding" v-if="bargainInfo.bargainUser && hasBargainUser">
					<view>已砍<text class="text-red">{{havCutPrice}}</text>元，还差<text class="text-red">{{numberUtil.numberSubtract(canCutPrice,havCutPrice)}}</text>元</view>
					<view class="cu-progress round margin-top">
						<view class="bg-red"  :class="'bg-'+theme.themeColor" :style="'width: ' + cutPercent">{{cutPercent}}</view>
					</view>
				</view>
				<view v-if="userInfo && bargainInfo.bargainUser && hasBargainUser">
					<view class="padding text-center" v-if="bargainInfo.bargainUser.userId != userInfo.id">
						<button class="cu-btn round bg-orange cuIcon-cardboardforbid lg" :class="'bg-'+theme.themeColor" :disabled="disabled" @tap="bargainCutSave" v-if="bargainInfo.enable == '1' && bargainInfo.bargainUser.status == '0' && !bargainInfo.bargainUser.bargainCut">帮砍一刀</button>
						<button class="cu-btn round bg-gray cuIcon-check lg" v-if="bargainInfo.bargainUser.status == '0' && bargainInfo.bargainUser.bargainCut">已经砍过了</button>
						<navigator class="cu-btn round bg-cyan lg margin-left" hover-class="none" :url="'/pages/bargain/bargain-detail/index?id=' + bargainInfo.id">发起新砍价</navigator>
					</view>
					<view class="padding text-center" v-if="(bargainInfo.bargainUser.status == '1' || bargainInfo.bargainUser.floorBuy == '0') && (bargainInfo.bargainUser.userId == userInfo.id)">
						<button class="cu-btn round bg-green.light lg" @tap="toBuy" v-if="(bargainInfo.bargainUser.status == '1' || bargainInfo.bargainUser.floorBuy == '0') &&  bargainInfo.bargainUser.isBuy == '0'">¥
							{{numberUtil.numberSubtract(bargainInfo.goodsSku.salesPrice,havCutPrice)}} 砍后价购买</button>
						<navigator hover-class="none" :url="'/pages/order/order-detail/index?id=' + bargainInfo.bargainUser.orderId"
						 class="cu-btn round bg-green.light lg" v-if="bargainInfo.bargainUser.isBuy == '1'">已经砍后价购买</navigator>
					</view>
				</view>
			</view>
		</view>

		<view class="cu-card mar-top-30" v-if="bargainCutList.length > 0">
			<view class="cu-item">
				<view class="cu-bar bg-white solid-bottom">
					<view class="action">
						<text class="cuIcon-titles text-xs" :class="'text-'+theme.themeColor"></text>砍价亲友团</view>
				</view>
				<view class="cu-list menu-avatar">
					<view class="cu-item" v-for="(item, index) in bargainCutList" :key="index">
						<view class="cu-avatar round lg" :style="'background-image:url(' + item.headimgUrl + ');'"></view>
						<view class="content">
							<view class="text-grey">{{item.nickName}}</view>
						</view>
						<view class="action margin-right text-red">
							<text class="text-price">{{item.cutPrice}}</text>
						</view>
					</view>
					<view class="cu-load bg-white" v-if="loadmore" @tap="loadMore">加载更多</view>
				</view>
			</view>
		</view>

		<view class="cu-card mar-top-30">
			<view class="cu-item">
				<view class="cu-bar bg-white">
					<view class="content">商品信息</view>
				</view>
				<view class="bg-white">
					<jyf-parser :html="article_description"></jyf-parser>
				</view>
				<view class="cu-load bg-gray to-down">已经到底啦...</view>
			</view>
		</view>

		<view :class="'cu-modal ' + modalRule">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">规则说明</view>
					<view class="action" @tap="ruleHide">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left">
					<text>{{bargainInfo.cutRule}}</text>
				</view>
			</view>
		</view>
		<view :class="'cu-modal ' + (bargainInfo.goodsSpu.shelf=='0'||!bargainInfo.goodsSku ? 'show' : '')">
			<view class="cu-dialog bg-white">
				<view class="cu-bar  justify-end">
					<view class="content">提示</view>
				</view>
				<view class="padding-xl">
					抱歉，该商品已下架
				</view>
				<view class="padding">
					<navigator open-type="navigateBack" class="cu-btn margin-top response lg" :class="'bg-'+theme.themeColor">
						确定
					</navigator>
				</view>
			</view>
		</view>
		<!-- 分享组件 -->
		<share-component v-model="showShare" :shareParams="shareParams"></share-component>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	import shopInfo from "components/shop-info/index";
	const util = require("@/utils/util.js");
	const {
		base64src
	} = require("utils/base64src.js");
	const app = getApp();
	import api from 'utils/api'
	import numberUtil from 'utils/numberUtil.js'
	import dateUtil from 'utils/dateUtil.js'
	import jweixin from 'utils/jweixin'
	import countDown from "components/count-down/index";
	import shareComponent from "@/components/share-component/index"

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				dateUtil: dateUtil,
				numberUtil: numberUtil,
				bargainInfo: {
					shopInfo:{},
					name:'',
					bargainUser: {
						launchNum: '',
						validBeginTime: '',
						validEndTime: ''
					},
					goodsSpu: {
						freightTemplat: {}
					},
					goodsSku: {
						specs: []
					},
				},
				disabled: false,
				page: {
					searchCount: false,
					current: 1,
					size: 10,
					ascs: '',
					//升序字段
					descs: 'create_time'
				},
				parameter: {},
				loadmore: true,
				bargainCutList: [],
				shareShow: '',
				curLocalUrl: '',
				userInfo: null,
				modalRule: '',
				id: "",
				specInfo: "",
				cutPercent: "",
				canCutPrice: "",
				havCutPrice: 0,
				posterUrl: "",
				posterShow: false,
				posterConfig: "",
				article_description: "",
				hasBargainUser: false, //是否存在砍价数据
				bargainUserId: '',
				showShare: false,
				shareParams: {

				}
			};
		},

		components: {
			shareComponent,
			countDown,
		},
		props: {},
		onShow() {
			if (this.bargainUserId) {
				api.bargainUserGet(this.bargainUserId).then(res => {
					let bargainUser = res.data;
					this.id = bargainUser.bargainId;
					this.bargainInfoGet({
						bargainId: this.id,
						id: bargainUser.id
					});
				});
			} else {
				this.bargainInfoGet({
					bargainId: this.id
				});
			}
		},
		onLoad(options) {
			//保存别人分享来的userCode
			util.saveSharerUserCode(options);
			this.dateUtil = dateUtil;
			this.numberUtil = numberUtil;
			let id;
			let bargainUserId;

			if (options.scene) {
				//接受二维码中参数
				let scenes = decodeURIComponent(options.scene).split('&');
				bargainUserId = scenes[0];
			} else if (options.bargainUserId) {
				//分享
				bargainUserId = options.bargainUserId;
			} else {
				id = options.id;
			}
			this.bargainUserId = bargainUserId;
			this.id = id;

			app.initPage().then(res => {
				this.userInfo = uni.getStorageSync('user_info');
			});
		},

		onShareAppMessage: function() {
			let bargainInfo = this.bargainInfo;
			let title = bargainInfo.shareTitle;
			let imageUrl = bargainInfo.picUrl;
			let path = '';

			if (bargainInfo.bargainUser && this.hasBargainUser) {
				path = 'pages/bargain/bargain-detail/index?bargainUserId=' + bargainInfo.bargainUser.id;
			} else {
				path = 'pages/bargain/bargain-detail/index?id=' + bargainInfo.id;
			}
			const userInfo = uni.getStorageSync('user_info')
			const userCode = userInfo ? '&sharer_user_code='+userInfo.userCode : ''
			path = path + userCode;
			return {
				title: title,
				path: path,
				imageUrl: imageUrl,
				success: function(res) {
					if (res.errMsg == 'shareAppMessage:ok') {
						console.log(res.errMsg);
					}
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {
			//查询砍价信息
			bargainInfoGet(data) {
				api.bargainInfoGet(data).then(res => {
					this.hasBargainUser = true;
					if (!res.data.bargainUser) {
						res.data.bargainUser = {
							validBeginTime: '',
							validEndTime: '',
						};
						this.hasBargainUser = false;
					}
					let bargainInfo = res.data;
					let goodsSku = bargainInfo.goodsSku;
					let specInfo = '';
					if(goodsSku&&goodsSku.specs)
					goodsSku.specs.forEach(function(specItem, index) {
						specInfo = specInfo + specItem.specValueName;
						if (goodsSku.specs.length != index + 1) {
							specInfo = specInfo + ';';
						}
					});
					this.bargainInfo = bargainInfo;
					this.specInfo = specInfo;
					if (this.hasBargainUser) {
						let canCutPrice = bargainInfo.goodsSku.salesPrice - bargainInfo.bargainPrice; //可砍
						let havCutPrice = bargainInfo.bargainUser.havBargainAmount; //已砍
						let cutPercent = Number(havCutPrice / canCutPrice * 100).toFixed(2) + '%';
						this.bargainInfo = bargainInfo;
						this.parameter.bargainUserId = bargainInfo.bargainUser.id;
						this.cutPercent = cutPercent;
						this.canCutPrice = canCutPrice;
						this.havCutPrice = havCutPrice;
						this.bargainCutList = [];
						this.bargainCutPage();
					}
					setTimeout(() => {
						this.article_description = bargainInfo.goodsSpu ? bargainInfo.goodsSpu.description:'';
					}, 300);
					this.initShareUrl();

				});
			},

			//帮砍记录列表
			bargainCutPage() {
				api.bargainCutPage(Object.assign({}, this.page, util.filterForm(this.parameter))).then(res => {
					let bargainCutList = res.data.records;
					this.bargainCutList = [...this.bargainCutList, ...bargainCutList];
					if (bargainCutList.length < this.page.size) {
						this.loadmore = false;
					}
				});
			},

			//发起砍价
			bargainUserSave() {
				this.disabled = true;
				api.bargainUserSave({
					bargainId: this.bargainInfo.id
				}).then(res => {
					this.bargainInfoGet({
						bargainId: this.id
					});
				});
			},

			loadMore() {
				this.page.current = this.page.current + 1;
				this.bargainCutPage();
			},
			initShareUrl(){
				// #ifdef H5
				this.curLocalUrl = util.setH5ShareUrl();
				if(!(this.curLocalUrl.indexOf('bargainUserId')!=-1)){
					if(this.bargainUserId){//先判断是否有传过来的砍价ID，如果有就用原有的
						this.curLocalUrl = this.curLocalUrl + '&bargainUserId=' + this.bargainUserId;
					}else if (this.bargainInfo.bargainUser && this.hasBargainUser) {
						this.curLocalUrl = this.curLocalUrl + '&bargainUserId=' + this.bargainInfo.bargainUser.id;;
					}
				}
				// 目前测试出的问题是：微信jsSDK分享的路径url必须 和 当前的页面路径一致，否则分享的链接会乱码，所以替换一下当前路径
				// 安卓有效，iOS微信浏览器有问题无法替换
				history.replaceState(history.state, null, this.curLocalUrl);
				// #endif

			},
			shareShowFun() {
				// #ifdef APP-PLUS
				this.curLocalUrl = util.setAppPlusShareUrl();
				if(this.bargainUserId){//先判断是否有传过来的砍价ID，如果有就用原有的
					this.curLocalUrl = this.curLocalUrl + '&bargainUserId=' + this.bargainUserId;
				}else if (this.bargainInfo.bargainUser && this.hasBargainUser && !(this.curLocalUrl.indexOf('bargainUserId')!=-1)) {
					this.curLocalUrl = this.curLocalUrl + '&bargainUserId=' + this.bargainInfo.bargainUser.id;;
				}
				// #endif

				let desc = '长按识别小程序码';
				let shareImg = this.bargainInfo.picUrl;
				// #ifdef H5 || APP-PLUS
					desc = '长按识别二维码';
				// #endif
					//海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
					let posterConfig = {
						width: 750,
						height: 1280,
						backgroundColor: '#fff',
						debug: false,
						blocks: [{
							width: 690,
							height: 808,
							x: 30,
							y: 183,
							borderWidth: 2,
							borderColor: '#f0c2a0',
							borderRadius: 20
						}, {
							width: 634,
							height: 74,
							x: 59,
							y: 770,
							backgroundColor: '#fff',
							opacity: 0.5,
							zIndex: 100
						}],
						texts: [{
							x: 30,
							y: 113,
							baseLine: 'top',
							text: this.bargainInfo.shareTitle,
							fontSize: 38,
							color: '#080808'
						}, {
							x: 92,
							y: 810,
							fontSize: 38,
							baseLine: 'middle',
							text: this.bargainInfo.goodsSpu.name,
							width: 570,
							lineNum: 1,
							color: '#080808',
							zIndex: 200
						}, {
							x: 59,
							y: 895,
							baseLine: 'middle',
							text: [{
								text: '底价',
								fontSize: 28,
								color: '#ec1731'
							}, {
								text: '¥' + this.bargainInfo.bargainPrice,
								fontSize: 36,
								color: '#ec1731',
								marginLeft: 30
							}]
						}, {
							x: 522,
							y: 895,
							baseLine: 'middle',
							text: '原价 ¥' + this.bargainInfo.goodsSku.salesPrice,
							fontSize: 28,
							color: '#929292'
						}, {
							x: 59,
							y: 945,
							baseLine: 'middle',
							text: [{
								text: this.bargainInfo.goodsSpu.sellPoint,
								fontSize: 28,
								color: '#929292',
								width: 570,
								lineNum: 1
							}]
						}, {
							x: 360,
							y: 1065,
							baseLine: 'top',
							text: desc,
							fontSize: 38,
							color: '#080808'
						}, {
							x: 360,
							y: 1123,
							baseLine: 'top',
							text: '快来帮好友砍一刀',
							fontSize: 28,
							color: '#929292'
						}],
						images: [{
							width: 634,
							height: 634,
							x: 59,
							y: 210,
							url: shareImg
						}, {
							width: 230,
							height: 230,
							x: 92,
							y: 1020,
							url: null,
							qrCodeName: 'qrCodeName',// 二维码唯一区分标识
						}]
					};
					let userInfo = uni.getStorageSync('user_info');

					if (userInfo && userInfo.headimgUrl) {
						//如果有头像则显示
						posterConfig.images.push({
							width: 62,
							height: 62,
							x: 30,
							y: 30,
							borderRadius: 62,
							url: userInfo.headimgUrl
						});
						posterConfig.texts.push({
							x: 113,
							y: 61,
							baseLine: 'middle',
							text: userInfo.nickName,
							fontSize: 32,
							color: '#8d8d8d'
						});
					}

				this.shareParams = {
					title: this.bargainInfo.shareTitle,
					desc: this.bargainInfo.goodsSpu.name,
					imgUrl: this.bargainInfo.picUrl,
					url: this.curLocalUrl,
					scene: this.bargainInfo.bargainUser.id,
					page: 'pages/bargain/bargain-detail/index',
					posterConfig: posterConfig
				}
				this.showShare = true;
			},
			//砍一刀
			bargainCutSave() {
				this.disabled = true;
				let bargainUserId = this.bargainInfo.bargainUser.id;
				api.bargainCutSave({
					bargainUserId: bargainUserId
				}).then(res => {
					let bargainCut = res.data;
					let that = this;
					uni.showModal({
						content: '恭喜为好友砍下' + bargainCut.cutPrice.toFixed(2) + '元',
						confirmColor: '#ff0000',
						success(res) {
							that.bargainInfoGet({
								bargainId: that.id,
								id: bargainUserId
							});
						}

					});
				});
			},

			ruleShow() {
				this.modalRule = 'show';
			},

			ruleHide() {
				this.modalRule = '';
			},

			//前去购买
			toBuy() {
				let bargainInfo = this.bargainInfo;
				let bargainUser = bargainInfo.bargainUser;
				let goodsSpu = bargainInfo.goodsSpu;
				let goodsSku = bargainInfo.goodsSku;
				/* 把参数信息异步存储到缓存当中 */

				uni.setStorage({
					key: 'param-orderConfirm',
					data: [{
						spuId: goodsSpu.id,
						skuId: goodsSku.id,
						quantity: 1,
						salesPrice: (goodsSku.salesPrice - this.havCutPrice).toFixed(2),
						spuName: goodsSpu.name,
						specInfo: this.specInfo,
						picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
						freightTemplat: goodsSpu.freightTemplat,
						weight: goodsSku.weight,
						volume: goodsSku.volume,
						orderType: '1',
						marketId: bargainInfo.id,
						relationId: bargainUser.id
					}]
				});
				uni.navigateTo({
					url: '/pages/bargain/bargain-order-confirm/index'
				});
			},

			countDownDone() {
				this.onLoad();
			}

		}
	};
</script>
<style>
	.row-img {
		width: 200rpx !important;
		height: 200rpx !important;
		border-radius: 10rpx
	}

	.bargain-btn{
		width: 580rpx;
		height: 76rpx;
	}

	.show-bg{
		height: 84%;
		margin-top: 120rpx;
	}

	.image-box{
		height: 90%;
	}

	.show-btn{
		margin-top: -130rpx;
	}
</style>
